package com.example.baseutils.usb;

import android.content.Context;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.util.Log;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class UsbDeviceUtil {
    private static final String TAG = "UsbDeviceUtil";
    public static List<UsbDevice> scan(Context context, final int vendorId, final int productId){
        final List<UsbDevice> usbDeviceList = new ArrayList<>();
        UsbManager usbManager = (UsbManager) context.getSystemService(Context.USB_SERVICE);
        if(usbManager != null){
            final HashMap<String, UsbDevice> deviceList = usbManager.getDeviceList();
            final Iterator<UsbDevice> iterator = deviceList.values().iterator();
            while (iterator.hasNext()){
                UsbDevice usb = iterator.next();
                if(usb != null){
                    Log.i(TAG, "scan: VendorId = " + vendorId + " ProductId = " + productId);
                    Log.i(TAG, "scan: " + usb.toString());
                    if(vendorId == usb.getVendorId() &&
                        productId == usb.getProductId()){
                        usbDeviceList.add(usb);
                    }
                }
            }
        }

        return usbDeviceList;
    }

    public static List<UsbDevice> scan(Context context){
        List<UsbDevice> usbDeviceList = null;
        UsbManager usbManager = (UsbManager) context.getSystemService(Context.USB_SERVICE);
        //所有连接上的USB设备
        if(usbManager != null){
            //VendorId = 6790 ProductId = 29987 //USB扫码器
            //VendorId = 7119 ProductId = 10436 //USB摄像头
            final HashMap<String, UsbDevice> deviceList = usbManager.getDeviceList();
            if(deviceList != null){
                final Set<Map.Entry<String, UsbDevice>> entries = deviceList.entrySet();
                if(entries.size() > 0){
                    usbDeviceList = new ArrayList<>();
                    final Iterator<Map.Entry<String, UsbDevice>> iterator = entries.iterator();
                    while (iterator.hasNext()){
                        final Map.Entry<String, UsbDevice> next = iterator.next();
                        final String key = next.getKey();
                        final UsbDevice usbDevice = next.getValue();
                        Log.e(TAG, "scan: key --> " + key);
                        Log.e(TAG, "scan: usbDevice-->" + usbDevice.toString());
                        usbDeviceList.add(usbDevice);
                    }
                }
            }
        }

        return usbDeviceList;
    }
}
